const express = require('express');
const router = express.Router();
const pool = require('../DB/db.js'); // 引入数据库连接池

router.use(express.json()); // 解析JSON请求体


router.get('/', async (req, res) => {
    const [rows] = await pool.execute('SELECT * FROM goods');
    res.send(rows);
});

// 获取购物车数据
router.get('/cartData', async (req, res) => {
    const [rows] = await pool.execute('SELECT * FROM cartdata');
    res.json(rows);
});

// 根据传入的id查询商品详情
router.get('/:id', async (req, res) => {
    const [rows] = await pool.execute('SELECT * FROM goods WHERE id = ?', [req.params.id]);
    res.send(rows);
});

// 加入购物车
router.post('/addCart', async (req, res) => {
    const { productId, title, price, num } = req.body;
    try {
        // 检查购物车中是否已有指定 productId 的商品
        const [existingProduct] = await pool.execute('SELECT * FROM cartdata WHERE productId =?', [productId]);
        if (existingProduct.length > 0) {
            const statue = existingProduct[0].statue;
            if (statue == '1') {
                // 商品存在且 statue 为 1，更新商品数量
                const updateSql = 'UPDATE cartdata SET num = num +? WHERE productId =?';
                const [updateResult] = await pool.execute(updateSql, [num, productId]);
                if (updateResult.affectedRows > 0) {
                    res.send({ code: 200, msg: '购物车商品数量更新成功' });
                } else {
                    res.send({ code: 500, msg: '购物车商品数量更新失败' });
                }
            } else if (statue == '2') {
                // 修改插入语句，将 statue 值设为 1
                const insertSql = 'INSERT INTO cartdata (productId, title, price, num, statue) VALUES (?, ?, ?, ?, 1)';
                const [insertResult] = await pool.execute(insertSql, [productId, title, price, num]);
                if (insertResult.affectedRows > 0) {
                    res.send({ code: 200, msg: '加入购物车成功' });
                } else {
                    res.send({ code: 500, msg: '加入购物车失败' });
                }
            }
        } else {
            // 商品不存在，添加商品且使其 statue 为 1
            const insertSql = 'INSERT INTO cartdata (productId, title, price, num, statue) VALUES (?, ?, ?, ?, 1)';
            const [insertResult] = await pool.execute(insertSql, [productId, title, price, num]);
            if (insertResult.affectedRows > 0) {
                res.send({ code: 200, msg: '加入购物车成功' });
            } else {
                res.send({ code: 500, msg: '加入购物车失败' });
            }
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ code: 500, msg: '服务器内部错误' });
    }
});    

// 更新订单支付状态
router.put('/updateOrderStatus/:id', async (req, res) => {
    try {
        const orderId = req.params.id;
        const [result] = await pool.execute('UPDATE cartdata SET statue = 2 WHERE id = ?', [orderId]);
        if (result.affectedRows > 0) {
            res.json({ code: 200, msg: '订单支付状态更新成功' });
        } else {
            res.json({ code: 404, msg: '未找到对应的订单' });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ code: 500, msg: '服务器内部错误' });
    }
});

// 删除订单
router.delete('/deleteOrder/:id', async (req, res) => {
    try {
        const orderId = req.params.id;
        const [result] = await pool.execute('DELETE FROM cartdata WHERE id = ?', [orderId]);
        if (result.affectedRows > 0) {
            res.json({ code: 200, msg: '订单删除成功' });
        } else {
            res.json({ code: 404, msg: '未找到对应的订单' });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ code: 500, msg: '服务器内部错误' });
    }
});

// 取消订单（删除未支付订单记录）
router.delete('/cancelOrder/:id', async (req, res) => {
    try {
        const orderId = req.params.id;
        // 确保只删除未支付的订单（statue 为 1）
        const [result] = await pool.execute('DELETE FROM cartdata WHERE id = ? AND statue = 1', [orderId]);
        if (result.affectedRows > 0) {
            res.json({ code: 200, msg: '未支付订单已取消' });
        } else {
            res.json({ code: 404, msg: '未找到对应的未支付订单' });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ code: 500, msg: '服务器内部错误' });
    }
});

module.exports =  router;